package com.yuyou.fn.common.util;

import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.exception.BusException;
import okhttp3.*;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/4/13.
 */
public class OkHttpClientUtils {

    private static final Logger log = LoggerFactory.getLogger(OkHttpClientUtils.class);

    private static final Charset UTF8 = Charset.forName("UTF-8");
    private static final MediaType FORM_CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    public static String okHttpPostByForm(String url, Map<String,String> params,int connectTimeout, int readTimeout){
        OkHttpClient client = new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(connectTimeout, TimeUnit.SECONDS ).readTimeout(readTimeout,TimeUnit.SECONDS).build();

        StringBuffer sb = new StringBuffer();
        //设置表单参数
        for (String key: params.keySet()) {
            sb.append(key+"="+params.get(key)+"&");
        }
        RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, sb.toString());


        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try{

            Response response = client.newCall(request).execute();
            if (response.code()!=200){
                throw new BusException("访问失败,url:"+url+"code:"+response.code());
            }else {
                String result=response.body().string();
                return result;
            }

        }catch (Exception e){
            throw new BusException(e.getMessage());
        }

    }

    public static OkHttpClient getIgnoreSsLClient(int connectTimeout, int readTimeout){
        OkHttpClient client = new OkHttpClient.Builder().hostnameVerifier(new HostnameVerifier(){
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).addInterceptor((chain)->{
            boolean compressed = false;

            Request request = chain.request();

            String curlCmd = "curl";
            curlCmd += " -X " + request.method();

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                String value = headers.value(i);
                if ("Accept-Encoding".equalsIgnoreCase(name) && "gzip".equalsIgnoreCase(value)) {
                    compressed = true;
                }
                curlCmd += " -H " + "\"" + name + ": " + value + "\"";
            }

            RequestBody requestBody = request.body();
            if (requestBody != null) {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                // try to keep to a single line and use a subshell to preserve any line breaks
                curlCmd += " --data $'" + buffer.readString(charset).replace("\n", "\\n") + "'";
            }

            curlCmd += ((compressed) ? " --compressed " : " ") + request.url();

            log.info("╭--- cURL (" + request.url() + ")");
            log.info(curlCmd);
            log.info("╰--- (copy and paste the above line to a terminal)");

            return chain.proceed(chain.request());
        }).retryOnConnectionFailure(false).connectTimeout(connectTimeout, TimeUnit.SECONDS ).readTimeout(readTimeout,TimeUnit.SECONDS).build();
        return client;
    }




}
